<template>
  <a-modal :visible="cvisible" :title="title" @ok="onOK" @cancel="onCancel">
    <a-form>
      <a-form-item label="编号" v-if="id">
        <a-input readonly :value="id"></a-input>
      </a-form-item>

      <a-form-item label="姓名" v-bind="validateInfos.name">
        <a-input v-model:value="dto.name"></a-input>
      </a-form-item>

      <a-form-item label="邮箱" v-bind="validateInfos.email">
        <a-input v-model:value="dto.email"></a-input>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import axios from "../../../api/request";
import { computed } from "vue";
import { UserSaveDto } from "../../../model/three/User";
import { useRequest } from "vue-request";
import {Form} from 'ant-design-vue'


const rules  = {
  name: [
    { required: true, message: '姓名不能为空', trigger: 'blur' },
    { min: 2, message: '长度大于等于2' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' }
  ]
};


const props = defineProps<{
  id: number;
  dto: UserSaveDto;
  cvisible: boolean;
}>();
const {validateInfos,validate} = Form.useForm(props.dto,rules)


const emit = defineEmits(["update:cvisible", "saved"]);

// const {runAsync: addUser} = useRequest<string,UserSaveDto[]>(
//   (dto)=>{
//     return axios.post('/api/userInsert',dto)
//   },
//   {
//     manual: true
//   }
// )

// const { runAsync: addUser } = useRequest(
//   (dto: UserSaveDto) => axios.post('/api/userInsert', dto),
//   { manual: true }
// )

const { run: addUser } = useRequest<string>(
  () =>
    axios.post<string>(`/api/userInsert`, props.dto).then((res) => {
      return res.data;
    }),
  {
    manual: true,
  }
);

const { runAsync: updateUser } = useRequest<string, UserSaveDto[]>(
  (dto) => {
    return axios.post(`/api/userUpdate/${props.id}`, dto);
  },
  {
    manual: true,
  }
);

async function onOK() {
  if (props.id === 0) {
    console.log("提交的数据", props.dto);
    await addUser();
    emit("update:cvisible", false);
    emit("saved","新增成功");
  } else {
    await validate()
    await updateUser();
    emit("update:cvisible", false);
    emit("saved","修改成功");
  }
}

function onCancel() {
  emit("update:cvisible", false);
}

const title = computed(() => {
  return props.id === 0 ? "新增" : "修改";
});
</script>